<template>
  <div class="file-manager">
    <el-row :gutter="20">
      <!-- 目录树 -->
      <el-col :span="8">
        <el-card header="目录导航">
          <el-radio-group v-model="file_path" size="small">
            <el-radio-button label="test_results" value="1" />
            <el-radio-button label="apks" value="2" />
            <el-radio-button label="media" value="3" />
          </el-radio-group>
          <el-input v-model="filterText" placeholder="过滤目录..." clearable />
          <el-tree
            ref="treeRef"
            :data="directoryTree"
            :props="defaultProps"
            :filter-node-method="filterNode"
            node-key="path"
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="tree-node">
                <el-icon
                  v-if="data.is_directory"
                  style="background-color: #42a5f5"
                >
                  <Folder />
                </el-icon>
                <el-icon v-else>
                  <Document />
                </el-icon>
                <span class="node-label">{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 文件列表 -->
      <el-col :span="16">
        <el-card :header="currentPath">
          <div class="file-actions">
            <el-button
              type="danger"
              :disabled="selectedFiles.length === 0"
              @click="handleDelete"
              v-if="userName == 'admin'"
            >
              删除选中文件 ({{ selectedFiles.length }})
            </el-button>
          </div>

          <el-table
            :data="fileList"
            @sort-change="handleSortChange"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column
              prop="name"
              label="文件名"
              sortable
              :sort-orders="['ascending', 'descending']"
            >
              <template #default="{ row }">
                <el-icon v-if="row.type == '目录'"><Folder /></el-icon>
                <el-icon v-else>
                  <Document />
                </el-icon>

                {{ row.name }}
              </template>
            </el-table-column>
            <el-table-column prop="size" label="大小" width="120">
              <template #default="{ row }">
                {{ formatFileSize(row.size) }}
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="100" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
  
  <script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Folder, Document } from '@element-plus/icons-vue'
import request from '@/utils/request'
import useUserStore from '@/store/modules/user'
import type { FilterNodeMethodFunction, TreeInstance } from 'element-plus'
const userInfo = useUserStore()
let userName = userInfo.username
console.log(userName)
// 响应式数据
const directoryTree = ref([])
const fileList = ref([])
const currentPath = ref('/')
const selectedFiles = ref([])
const filterText = ref('')
const treeRef = ref<any>()
const file_path = ref('1')

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
watch(file_path, (val) => {
  fetchDirectoryTree()
})
// 树形配置
const defaultProps = {
  children: 'children',
  label: 'label',
}
//排序
const handleSortChange = ({ column, prop, order }: any) => {}
const filterNode = (value: any, data: any) => {
  if (!value) return true
  return data.label.includes(value)
}

// 方法
const fetchDirectoryTree = async () => {
  try {
    // 使用 axios 发起 GET 请求(推荐)
    request
      .get('/nimi/auth/files/list-directory', {
        params: { file_path: file_path.value }, // 查询参数
        headers: {},
      })
      .then((response) => {
        directoryTree.value = response.data
        console.log(response.data)
      })
      .catch((error) => {
        console.error(error)
      })
  } catch (error) {
    ElMessage.error('获取目录树失败')
    console.error(error)
  }
}

const fetchFileList = async (path: any) => {
  try {
    // 使用 axios 发起 GET 请求(推荐)
    const response = await request.get(
      `/nimi/auth/files/file-list?path=${encodeURIComponent(path)}`,
      {
        params: {}, // 查询参数
        headers: {},
      },
    )
    console.log(response.data)
    fileList.value = response.data
  } catch (error) {
    ElMessage.error('获取文件列表失败')
  }
}

const handleNodeClick = (data: any) => {
  // console.log(data)
  // if (data.is_directory) {
  currentPath.value = data.path
  fetchFileList(data.path)
  // }
}

const handleSelectionChange = (selection: any) => {
  selectedFiles.value = selection.map((item: any) => item.path)
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`,
      '警告',
      { type: 'warning' },
    )
    // 使用 axios 发起 POST 请求
    const response: any = await request.post(
      '/nimi/auth/files/delete-files',
      JSON.stringify({ paths: selectedFiles.value }),
      {
        headers: { 'Content-Type': 'application/json' },
      },
    )
    if (response.code == 200) {
      const result = await response.data

      if (result.errors.length > 0) {
        ElMessage.warning(`部分文件删除失败: ${result.errors.join('; ')}`)
      } else {
        ElMessage.success(`成功删除 ${result.deleted.length} 个文件`)
      }

      // 刷新列表
      fetchFileList(currentPath.value)
      fetchDirectoryTree()
      selectedFiles.value = []
    } else {
      ElMessage.error(response.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除操作失败')
    }
  }
}

// 工具函数
const formatFileSize = (bytes: any) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 生命周期
onMounted(() => {
  fetchDirectoryTree()
})
</script>
<style scoped lang="scss">
// .tree-node {
//   background-color: rgba(50, 13, 187, 0.2);
// }
</style>